package com.yanqu.road.message;

import com.google.protobuf.Message;
import com.yanqu.road.define.YanQuMessageDefine;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;

import java.io.IOException;
import java.util.List;

public class YanQuMessageEncrypt extends MessageToMessageEncoder<YanQuMessage> {


    private int getMessageSize(Message pbMessage, YanQuMessage message) {
        int size = YanQuMessageDefine.HEADER_SIZE;
        if (pbMessage == null) {
            byte[] bytes = message.getBytes();
            if (bytes != null) {
                size = YanQuMessageDefine.HEADER_SIZE + bytes.length;
            }
        } else {
            size = YanQuMessageDefine.HEADER_SIZE + pbMessage.getSerializedSize();
        }

        return size;
    }

    @Override
    protected void encode(ChannelHandlerContext ctx, YanQuMessage msg, List<Object> out) throws Exception {
        Object msgObject = msg.getMyMsg();
        if (msgObject != null && msgObject instanceof YanQuMessageBuffer) {
            for (YanQuMessage yanQuMessage : (YanQuMessageBuffer) msgObject) {
                encodeYanquMessage(ctx, yanQuMessage, out);
            }
        } else {
            encodeYanquMessage(ctx, msg, out);
        }
    }

    private void encodeYanquMessage(ChannelHandlerContext ctx, YanQuMessage message, List<Object> out) throws IOException {
        Message pbMessage = message.getMessage();
        int messageSize = getMessageSize(pbMessage, message);
        ByteBuf byteBuf = ctx.alloc().buffer(messageSize);
        message.writeHeader(messageSize, byteBuf);
        out.add(byteBuf);
    }


}
